package org.xczy.boot.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.xczy.boot.entity.User;
import org.xczy.boot.result.Result;
import org.xczy.boot.service.UserService;
import org.xczy.boot.utils.RedisUtil;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

  @Resource
  private UserService userService;

  @PostMapping("/add")
  public Result<String> addUser(@RequestBody User user){
    if(StringUtils.isEmpty(user) || user.getName() == null || user.getPassword() == null){
      return Result.fail("参数错误");
    }
    int i = userService.addUser(new User(null, user.getName(), user.getPassword(),"root", null, null));
    if(i > 0){
      return  Result.ok("添加成功");
    }
    if(i < 0){
      return Result.fail("该用户已存在");
    }
    return Result.fail("添加失败");
  }

  @DeleteMapping("/{id}")
  public Result<String> deleteById(@PathVariable("id") Integer id){
    if(id == null){
      return Result.fail("删除失败，id不能为空");
    }
    int i = userService.deleteById(id);
    if(i > 0){
      return Result.ok("删除成功");
    }
    return Result.fail("删除失败，用户不存在");
  }

  @PutMapping("/update")
  public Result<String> updateById(@RequestBody User user){
    if(StringUtils.isEmpty(user) || user.getId() == null){
      return Result.fail("参数错误");
    }
    int i = userService.updateById(user);
    if(i > 0){
      return Result.ok("更新成功");
    }
    return Result.fail("更新失败");
  }

  @GetMapping("/{id}")
  public Result<Object> getUserById(@PathVariable("id") Integer id){
    if(id == null){
      return Result.fail("id不能为空");
    }
    User user = userService.getUserById(id);
    return Result.ok(user);
  }

  @GetMapping("/all")
  public Result<List<User>> getAllUser(){
    return Result.ok(userService.getAllUser());
  }

  @PostMapping("/login")
  public Result<String> login(@RequestBody User user){
    User loginUser = userService.login(user);
    if(loginUser == null){
      return  Result.fail("登录失败，用户名或密码错误");
    }
    return Result.ok("登录成功");
  }
}
